var host = "http://admin.testmorefun.chinamcloud.com";

var uid = getQueryString('uid')||'oPrjmv74tkApYDUxTr7-0xbSxgmI';
var act_id = getQueryString('act_id')||'74a1f3e0-acf5-46c1-b088-0bcf62631eb9';
var vote_token = getQueryString('vote_token')||'876415e4350c81b6075e906fd5970a5e';

//抽奖次数限制
var limitNum = 0;
//活动是否允许分享
var canShared;
//活动规则
var actRule = '';

var api = {
	//判断用户是否有抽奖(游戏)资格
	eligibleToPlay: function(cb){
		$.ajax({
			url: host + '/lua/api/draw/allowed',
			data: {
				uid: uid,
				act_id: act_id,
				vote_token: vote_token
			},
			success: function(res){
				if (res.code == 200) {
					limitNum = res.data.surplus_times;
					if (cb){
						cb(limitNum)
					}
				} else {
					Toast(res.message);
				}
			}
		})
	},
	//获取活动参数
	getGameConfig: function (type,cb) {  //type: 'eat-chicken'
		$.ajax({
			url: host + '/lua/api/draw/summary',
			data: {
				act_id: act_id,
				type: type
			},
			success: function(res){
				if (res.code === 200) {
					canShared = res.data.activity.shares.isopen == 'on'? true: false;
					actRule = res.data.activity.description;
					if(cb){
						cb(res.data);
					}
				} else {
					Toast('游戏数据获取失败');
				}
			}
		})
	},
	//抽奖接口
	lottery: function (type,callbackFn) {
		$.ajax({
			url: host + '/lua/api/draw/random',
			data: {
				act_id: act_id,
				type: type,
				uid: uid
			},
			success: callbackFn
		})
	},
	//我的中奖纪录
	myPrize: function (per_page, page, cb) {
		$.ajax({
			url: host + '/api/winnings/' + act_id,
			data: {
				uid: uid,
				per_page: per_page,
				page: page
			},
			success: cb
		})
	},
	onShareAfter: function(){
		$.ajax({
			url: host + '/lua/api/communal/allowed',
			data:{
				act_id: act_id,
				uid: uid
			},
			success: function(){

			}
		})
	}
};
//生成弹框Dom
function createToast () {
	var html = '<div id="toast-box" style="width:100%;height: 100%;position: fixed;top:0;left:0;display: none;z-index:9999;">'+
			       '<div id="toast-content" style="font-size: 14px;color: #ffffff;background: rgba(0,0,0,.7);border-radius: 10px;height: 45px;line-height: 45px;padding:0 10px;letter-spacing: 1px;position: absolute;top:0;bottom:0;margin: auto;left: 50%;transform: translateX(-50%);">'+
				   '</div>'+
	           '</div>';
	$('body').append(html);
};
createToast();

//抽奖弹框
function createLotteryBox(){
	var html =  '<div id="lotteryfailwrapper" style="position: fixed;top: 0;left: 0;width: 100%;height: 100%;background: rgba(0,0,0,.8);z-index: 999;display:none;">'+
		            '<div style="width: 5.25rem;height: 5.16rem;position: absolute;left:0;right:0;margin: auto;top:2.77rem;background: url(../utils/img/lotteryfailbox.png);background-size: 100% 100%;">'+
		                '<div onclick="playAgain()" style="width:3.38rem;height: .8rem;position: absolute;left:0;right:0;margin: auto;bottom: .62rem;"></div>'+
		                '<div onclick="closeLotteryBox()" style="width:.65rem;height: .64rem;position: absolute;left:0;right:0;margin:auto;bottom: -1.4rem;background: url(../utils/img/close.png);background-size: 100% 100%;"></div>'+
		            '</div>'+
		        '</div>'+
		        '<div id="lotterysuccesswrapper" style="display:none;position: fixed;top: 0;left: 0;width: 100%;height: 100%;background: rgba(0,0,0,.8);z-index: 999;">'+
		        	'<div style="width:5.25rem;height: 6.16rem;position: absolute;left:0;right:0;margin: auto;top:1.76rem;background: url(../utils/img/lotterysuccessbox.png);background-size: 100% 100%;">'+
			            '<div style="line-height: .57rem;font-size: .25rem;color:#000000;padding-top:.9rem;text-align: center;">获得奖品【<span id="win-name">iPhoneX</span>】</div>'+
			            '<div id="win-img" style="width:100%;height: 2rem;margin-top: .44rem;background-size: auto 100%;background-position: center 0;background-repeat: no-repeat;background-image: url(../utils/img/iphonex.jpg);"></div>'+
			            '<div style="font-size: .16rem;color: #30302f;width:100%;text-align: center;line-height: 1.1;margin-top: .64rem;">有效期：<span id="win-date">2018/03/25~2018/04/25</span></div>'+
			            '<div onclick="playAgain()" style="width:3.38rem;height: .8rem;position: absolute;left:0;right:0;margin: auto;bottom:.36rem;"></div>'+
			            '<div onclick="closeLotteryBox()" style="width:.65rem;height: .64rem;position: absolute;left:0;right:0;margin:auto;bottom: -1.4rem;background: url(../utils/img/close.png);background-size: 100% 100%;"></div>'+
			        '</div>'+
		        '</div>';
    $('body').append(html);
};
createLotteryBox();

//提示弹框
function Toast(text){
	$('#toast-content').text(text);
	$('#toast-box').show();
	setTimeout(function(){
		$('#toast-box').hide();
	},1000);
};

function onToast(text,time){
	$('#toast-content').text(text);
	$('#toast-box').show();
	if(time){
		setTimeout(function(){
			$('#toast-box').hide();
		},time)
	}
}

function offToast(){
	$('#toast-box').hide();
}

//关闭未中奖盒子
function closeLotteryBox(){
	$('#lotteryfailwrapper,#lotterysuccesswrapper').hide();
}

//再玩一次
function playAgain() {
	$('#successPage,#failPage,#lotteryfailwrapper,#lotterysuccesswrapper').hide();
	$('#startPage').show();
}

//获取url参数
function getQueryString(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    }
    return null;
};
//点击抽奖按钮
function drawALottery() {
	if (limitNum <= 0) {
		Toast('抽奖次数不够');
		return;
	}
	onToast('抽奖中..');
	api.lottery(gameName, function (res) {
		offToast();
		if (res.data.is_winning) {
			var prize = res.data.prize;
			var name = prize.name;
			var img = prize.image;
			var date = prize.expired_start_date+'/'+prize.expired_end_date;
			lotteryResult.win(name, img, date);
		} else {
			lotteryResult.fail();
		}
		
	});
}

//抽奖结果
var lotteryResult = {
	fail: function () {
		$('#lotteryfailwrapper').show();
	},
	win: function (name, img, date) {
		$('#win-name').html(name);
		$('#win-img').css('background-image', 'url('+img+')');
		$('#win-date').html(date);
		$('#lotterysuccesswrapper').show();
	}
};
//------------------------设置底部跳转----------------------------
function setFootLink(el){
	var p = $('<p class="linkLine" style="position: absolute;left: 0;bottom:10px;width: 100%;text-align: center;font-size: 14px;margin-bottom:0;color: white;z-index: 12;"></p>');
	var toRule = $(`<a href="javascript:void(0);" onclick="goToRule()" style="color: inherit">活动规则</a>`);
	var toRecord = $(`<a href="../common/prize.html?uid=${uid}&act_id=${act_id}" style="color: inherit">我的奖品</a>`);
	var line = $('<span style="padding: 0 15px">|</span>');
	p.append(toRule,line,toRecord);
	if ($('.linkLine').length) {
		$('.linkLine').remove();
	}
	if(el){
		$(el).append(p)
	}else{
		$('body').append(p);
	}
}
function goToRule() {
	localStorage.setItem('gamerule', actRule);
	window.location.href = "../common/rule.html";
}
setFootLink();
//----------------分享--------------------
function loadScript(fn){ //加载jssdk
	var jsNode = document.createElement('script');
	var body = document.getElementsByTagName('body')[0];
	jsNode.setAttribute('type','text/javascript');
	jsNode.setAttribute('src','http://res.wx.qq.com/open/js/jweixin-1.2.0.js');
	body.appendChild(jsNode);
	jsNode.onload = function(){
		fn();
	}
}
function share(type){
	loadScript(function(){
		api.getGameConfig(type,function(result){
			console.log(result);
			let url = window.location.href.split('#')[0];
			$.ajax({
				url: 'http://admin.testmorefun.chinamcloud.com/api/configurations/wechat/js-sdk',
				data:{
					url: url
				},
				type: 'post',
				success:function(data1){
					var  data = data1.data;
					var shareLink = window.location.origin + '/wechat/shares?id=' + act_id;
					//配置微信分享
					wx.config({
						debug: false,
						appId: data.appId,
						timestamp: data.timestamp,
						nonceStr: data.nonceStr,
						signature: data.signature,
						jsApiList: [
							'checkJsApi',
							'onMenuShareTimeline',
							'onMenuShareAppMessage',
							'onMenuShareQQ',
							'onMenuShareWeibo',
							"hideMenuItems"
						]
					});
					wx.ready(function () {
						if(result.activity.shares.isopen == 'off'){
							wx.hideOptionMenu();
							return;
						}
						var shares = result.activity.shares;
						//分享给好友
						wx.onMenuShareAppMessage({
							title: shares.title,
							desc: shares.content,
							link: shareLink,
							imgUrl: shares.thumb,
							success: function (res) {
								onToast('分享成功',2000);
								api.onShareAfter();
							},
							cancel: function (res) {
								onToast('您已取消分享',2000);
							},
							fail: function (res) {
								onToast('分享失败',2000);
							}
						});
						//分享到朋友圈
						wx.onMenuShareTimeline({
							title: shares.title,
							desc: shares.content,
							link: shareLink,
							imgUrl: shares.thumb,
							success: function (res) {
								onToast('分享成功',2000);
								api.onShareAfter();
							},
							cancel: function (res) {
								onToast('您已取消分享',2000);
							},
							fail: function (res) {
								onToast('分享失败',2000);
							}
						});
						//分享到qq
						wx.onMenuShareQQ({
							title: shares.title,
							desc: shares.content,
							link: shareLink,
							imgUrl: shares.thumb,
							success: function (res) {
								onToast('分享成功',2000);
								api.onShareAfter();
							},
							cancel: function (res) {
								onToast('您已取消分享',2000);
							},
							fail: function (res) {
								onToast('分享失败',2000);
							}
						});
						//获取“分享到腾讯微博”按钮点击状态及自定义分享内容接口
						wx.onMenuShareWeibo({
							title: shares.title,
							desc: shares.content,
							link: shareLink,
							imgUrl: shares.thumb,
							success: function (res) {
								onToast('分享成功',2000);
								api.onShareAfter();
							},
							cancel: function (res) {
								onToast('您已取消分享',2000);
							},
							fail: function (res) {
								onToast('分享失败',2000);
							}
						});

						///获取“分享到QQ空间”按钮点击状态及自定义分享内容接口
						wx.onMenuShareQZone({
							title: shares.title,
							desc: shares.content,
							link: shareLink,
							imgUrl: shares.thumb,
							success: function (res) {
								onToast('分享成功',2000);
								api.onShareAfter();
							},
							cancel: function (res) {
								onToast('您已取消分享',2000);
							},
							fail: function (res) {
								onToast('分享失败',2000);
							}
						});
					});
				}
			});
		});
	});
}